package com.map.domain;
import java.io.*;
import java.util.*;

public class Node  implements Serializable {
  
  // Data Fields
  
  /** The information stored in this node. */
  public String name;
  /** Reference to the left child. */
  public List<Node> children;
  
  // Constructors
  /**
   * Construct a node with given data and no children.
   * @param data The data to store in this node
   */
  public Node(String data) {
    this.name = data;
    children = null;
  }
  
  public Node(String data, Node child) {
    this.name = data;
    children = new LinkedList<Node>();
    children.add(child);
  }
  
  // Methods
  /**
   * Returns a string representation of the node.
   * @return A string representation of the data fields
   */
  private boolean compare(String a, String b) {
	  boolean result = true;
	  
	  int x = 0, y = 0;
	  boolean aIsInt = true;
	  boolean bIsInt = true;
	  
	  try {
		  x = Integer.parseInt(a);
	  } catch (NumberFormatException e) {
		  aIsInt = false;
	  }
	  
	  try {
		  y = Integer.parseInt(b);
	  } catch (NumberFormatException e) {
		  bIsInt = false;
	  }
	  
	  if (aIsInt && !bIsInt) {
		  result = true;
	  } else
	  if (aIsInt && bIsInt) {
		  result = x < y;
	  } else
	  if (!aIsInt && bIsInt) {
		  result = false;
	  } else
	  if (!aIsInt && !bIsInt) {
		  if (a.length() < b.length()) {
			  result = true;
		  } else
		  if (a.length() > b.length()) {
			  result = false;
		  } else { 
			  result = a.compareTo(b) < 0;
		  }
	  }

//	  System.out.println(result);
	  return !result;
  }
  
  @Override
  public String toString() {
    String s = name.toString();
//    if (left == null ) s += " left is null";
//    if (right == null ) s += " right is null";
    return s;
  }
  
  public String getName() {
    return name;
  }
  
  public void setName(String newData) {
    name = newData;
  }
  
  public List<Node> getChildren() {
    return children;
  }
  
  public void addChild(Node child) {
	  if (children == null) {
		  children = new LinkedList<Node>();
		  children.add(child);
	  } else
	  {
		  int i = 0;
		  while (i < children.size() && !compare(children.get(i).name, child.name)) i ++;
		  if (i == children.size()) {
			  children.add(child);
		  } else {
			  children.add(i, child);
		  }
	  }
  }
  
  public void setChildren(List<Node> children) {
	 this.children = children;
  }

public Node hasChild(String child) {
	if (children == null) return null;
	System.out.println(children.size());
	for (int i = 0; i < children.size();i ++) {
		System.out.println("Compare: ");
		System.out.println(children.get(i).getName());
		System.out.println(child);
		if (children.get(i).getName().equals(child)) {
			System.out.println("Sorry ei, the node has already has the passed in node");
			return children.get(i);
		}
	}
	return null;
}
}

